package com.me.learnspring.controller;

import com.me.learnspring.controller.request.NewCategoryRequest;
import com.me.learnspring.model.Category;
import com.me.learnspring.model.Drink;
import com.me.learnspring.repository.DrinkRepository;
import com.me.learnspring.service.CategoryService;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private DrinkRepository drinkRepository;
	
	@GetMapping(value = "/",params = "!name")
	public ModelAndView getAll(){
		ModelAndView mv = new ModelAndView("category/index");
		List<Category> categoryList = categoryService.findAll();
		mv.addObject("clist", categoryList);
		return mv;
	}
	
	// @GetMapping("/")
	// public List<Category> getAll(){
	// 	return categoryService.findAll();
	// }
	
	@GetMapping(value = "/",params = "name")
	public Category getCategory(String name){
		return categoryService.findOne(name);
	}
	
	@GetMapping("/{id}")
	public Category getCategory(@PathVariable Long id){
		return categoryService.findById(id);
	}
	
	// @PostMapping("/save")
	// @ResponseStatus(code = HttpStatus.CREATED)
	// public Category getCategory(Category category){
	// 	return categoryService.saveCategory(category);
	// }
	
	@PostMapping(value = "/save",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	@ResponseStatus(code = HttpStatus.CREATED)
	public Category saveCategory(NewCategoryRequest categoryRequest){
		Category category = new Category();
		BeanUtils.copyProperties(categoryRequest,category);
		
		return categoryService.saveCategory(category);
	}
	
	@PostMapping(value = "/save",consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseStatus(code = HttpStatus.CREATED)
	public Category saveCategoryFromJson(@RequestBody NewCategoryRequest categoryRequest){
		Category category = new Category();
		BeanUtils.copyProperties(categoryRequest,category);
		
		return categoryService.saveCategory(category);
	}
}
